<template>
  <div class="app-container">

    <el-card class="box-card"  style="border-radius: 10px;" v-show="showSearch" >
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"

      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="电路类型" prop="circuitTypeId">
        <el-select
          v-model="queryParams.circuitTypeId"
          placeholder="请选择类型"
          clearable
          size="small"
        >
          <el-option
            v-for="(item, index) in circuitTypeList"
            :label="item.name"
            :value="item.id"
            :key="index"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="可用状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择类型"
          clearable
          size="small"
        >
          <el-option
            v-for="(stateTypeItem, stateTypeIndex) in stateTypeEnum"
            :label="stateTypeItem.name"
            :value="stateTypeItem.value"
            :key="stateTypeIndex"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>

  <el-card class="box-card margin_t10"  style="border-radius: 10px;" >

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="circuitParamRefresh"
        >属性更新
        </el-button>
      </el-col>

      <el-col :span="1.5" v-show="true">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="stepBarDialog = true"
        >步骤条
        </el-button>
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getCircuitList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="circuitList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column
        label="电路类型"
        align="center"
        prop="circuitType.name"
      />
      <el-table-column label="采集类型" align="center" prop="signalType">
        <template slot-scope="scope">
          <span>{{ GlobalVariable.getSignalType(scope.row.signalType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="存储类型" align="center" prop="storageType">
        <template slot-scope="scope">
          <span>{{
            GlobalVariable.getStorageType(scope.row.storageType)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用状态" align="center">
        <template v-if="scope.row.state" slot-scope="scope">
          <span>{{ scope.row.state === "YES" ? "可用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="插入时间" align="center" prop="insertTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.insertTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="用户编号" align="center" prop="userId"/>-->
      <!--      <el-table-column label="原理图路径" align="center" prop="path"/>-->
      <el-table-column
        label="配置"
        width="140px"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="execute(scope.row)"-->
          <!--            v-hasPermi="['edsta:rule:edit']"-->
          <!--          >执行脚本-->
          <!--          </el-button>-->
          <el-button
            size="small"
            type="primary"
            plain

            style="width: 80px;"
            @click="openAttributeEditDialog(scope.row)"
            >属性配置
          </el-button>
          <el-tooltip class="item" effect="dark" content="电路生成规则配置" placement="left-start">

          <el-button
            size="small"
            type="primary"
            plain

            style="margin: 5px 0 0 0;width: 80px;"
            @click="openDataRules(scope.row)"
            >规则配置
          </el-button>
        </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getCircuitList"
    />

  </el-card>

    <!-- 电路文件上传对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="电路文件上传"
      :visible.sync="circuitFilesImportDialog"
      width="700px"

      append-to-body
    >
      <template>
        <div style="height: 200px">
          <!--          <el-button @click="showFileList">显示</el-button>-->
          <uploader
            ref="uploadCircuitFilesImport"
            :options="this.circuitFilesImportOptions"
            @file-success="cfSuccess"
            @file-added="cfAdd"
          >
            <uploader-btn class="myUploader" :directory="true">选择文件目录</uploader-btn>
            <uploader-list>
              <!--通过slot-scope绑定文件实例-->
              <div slot-scope="props">
                <div v-for="(file,i) in props.fileList" :key="i" style="width: 100%">
                  <el-row>
                    <el-col :span="3">
                      <el-button @click="clearCircuitFilesImportList(file)">删除</el-button>
                    </el-col>
                    <el-col :span="21">
                      <uploader-file :list="true" :file="file" ></uploader-file>
                    </el-col>
                  </el-row>

                </div>
              </div>
            </uploader-list>
          </uploader>
        </div>
      </template>
    </el-dialog>


    <el-dialog
      :close-on-click-modal="false"
      title="文件库文件缺失列表"
      :visible.sync="documentLibraryListDialog"
      width="1000px"
      append-to-body
    >
      <el-button
        v-if="documentLibraryJsonArray.length > 0"
        type="warning"
        plain
        size="mini"
        @click="documentLibraryDownload"
      >下载列表
      </el-button>
      <div
        v-loading="documentLibraryLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-input
          class="fileLackInput"
          v-for="key in documentLibraryJsonArray"
          :value=key
          disabled
          type="textarea"
          resize="none"
          style="margin-top: 3px; "
        />
      </div>
    </el-dialog>

    <!-- 电路未被记录对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="电路未被记录列表"
      :visible.sync="circuitNoExistListDialog"
      width="1000px"
      append-to-body
    >
      <el-button
        v-if="noExistMap.jsonArray.length > 0"
        type="warning"
        plain
        size="mini"
        @click="noExistDownload"
      >下载列表
      </el-button>
      <div >
        <el-input
          class="fileLackInput"
          v-for="key in noExistMap.jsonArray"
          :value=key
          disabled
          type="textarea"
          resize="none"
          style="margin-top: 3px; "
        />
      </div>
      <div>
        <el-pagination
          background
          layout="prev, pager, next"
          :total=noExistMap.total
          :current-page=noExistMap.page
          @prev-click="noExistPrevClick"
          @next-click="noExistNextClick"
        >
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 电路文件缺失对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="电路文件缺失列表"
      :visible.sync="circuitFileLackListDialog"
      width="1000px"
      append-to-body
    >
      <el-button
        v-if="fileLackMap.jsonArray.length > 0"
        type="warning"
        plain
        size="mini"
        @click="lackListDownload"
      >下载缺失列表
      </el-button>
      <div >
        <el-input
          class="fileLackInput"
          v-for="key in fileLackMap.jsonArray"
          :value=key
          disabled
          type="textarea"
          resize="none"
          style="margin-top: 3px; "
        />
      </div>
      <div>
        <el-pagination
          background
          layout="prev, pager, next"
          :total=fileLackMap.total
          :current-page=fileLackMap.page
          @prev-click="fileLackPrevClick"
          @next-click="fileLackNextClick"
        >
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 匹配规则对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="属性配置"
      :visible.sync="attributeEditDialog"
      width="1200px"
      append-to-body
    >
      <attribute-edit
        @close="closeAttributeEditDialog"
        ref="refScript"
        v-if="attributeEditDialog"
        :circuit-id="circuitId"
      />
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button  type="primary"  @click="saveAttribute">保 存</el-button>-->
      <!--        <el-button @click="attributeEditDialog = false">关 闭</el-button>-->
      <!--      </div>-->
    </el-dialog>

    <!-- 添加或修改电路模板对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        v-if="open"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="电路类型" prop="circuitTypeId">
          <el-select
            v-model="form.circuitTypeId"
            placeholder="请选择类型"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in circuitTypeList"
              :label="item.name"
              :value="item.id"
              :key="index"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="采集类型" prop="signalType">
          <el-select
            v-model="form.signalType"
            placeholder="请选择类型"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in signalTypeEnum"
              :label="item.name"
              :value="item.value"
              :key="index"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="存储类型" prop="storageType">
          <el-select
            v-model="form.storageType"
            placeholder="请选择类型"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in storageTypeEnum"
              :label="item.name"
              :value="item.value"
              :key="index"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="存储容量(MB)" prop="storageCapacity">
          <el-input
            v-model="form.storageCapacity"
            placeholder="请输入存储容量"
          />
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select
            v-model="form.state"
            placeholder="请选择类型"
            clearable
            size="small"
          >
            <el-option
              v-for="(stateTypeItem, stateTypeIndex) in stateTypeEnum"
              :label="stateTypeItem.name"
              :value="stateTypeItem.value"
              :key="stateTypeIndex"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="插入时间" prop="insertTime">-->
        <!--          <el-date-picker clearable size="small"-->
        <!--                          v-model="form.insertTime"-->
        <!--                          type="date"-->
        <!--                          value-format="yyyy-MM-dd"-->
        <!--                          placeholder="选择插入时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="原理图路径" prop="path">-->
        <!--          <el-input v-model="form.path" type="textarea" placeholder="请输入内容"/>-->
        <!--        </el-form-item>-->

        <el-form-item label="缩略图" prop="thumbnailPath">
          <el-upload
            class="upload-demo"
            :action="url"
            :headers="myHeaders"
            :file-list="thumbnailFileList"
            :on-remove="thumbnailHandleRemove"
            :on-success="thumbnailUploadSuccess"
            :limit="1"
            :multiple="false"
            list-type="picture"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单张图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图" prop="thumbPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="thumbFileList"
            :on-remove="thumbHandleRemove"
            :on-success="thumbUploadSuccess"
            :limit="1"
            :multiple="false"
            list-type="picture"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单张图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="图表" prop="chartsPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="chartsFileList"
            :on-remove="chartsHandleRemove"
            :on-success="chartsUploadSuccess"
            :limit="1"
            :multiple="false"
            list-type="picture"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单张图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="模板工程" prop="projectPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="projectFileList"
            :on-remove="projectHandleRemove"
            :on-success="projectUploadSuccess"
            :limit="1"
            :multiple="false"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="bom表" prop="bomPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="bomFileList"
            :on-remove="bomHandleRemove"
            :on-success="bomUploadSuccess"
            :limit="1"
            :multiple="false"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="网络替换表" prop="netPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="netFileList"
            :on-remove="netHandleRemove"
            :on-success="netUploadSuccess"
            :limit="1"
            :multiple="false"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="位号替换表" prop="designatorsPath">
          <el-upload
            :action="url"
            :headers="myHeaders"
            :file-list="designatorsFileList"
            :on-remove="designatorsHandleRemove"
            :on-success="designatorsUploadSuccess"
            :limit="1"
            :multiple="false"
            :data=uploadDateParam
            :before-upload="uploadDateSet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行脚本弹窗 -->
    <el-dialog
      title="执行脚本"
      :visible.sync="openExecute"
      width="800px"
      append-to-body
    >
      <el-form
        ref="scriptForm"
        :model="scriptForm"
        :rules="scriptRules"
        label-width="80px"
      >
        <el-form-item label="电路模板名称" prop="sceneName">
          <el-input v-model="scriptForm.sceneName" disabled />
        </el-form-item>
        <el-form-item label="运行脚本" prop="runScript">
          <el-select
            v-model="scriptForm.runScript"
            placeholder="请选择脚本"
            clearable
            size="small"
          >
            <el-option
              v-for="item in scriptList"
              :label="item.name"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="输入参数" prop="inputParameter">
          <el-input v-model="scriptForm.inputParameter" disabled />
        </el-form-item>
        <el-form-item label="输入变量" prop="variable">
          <el-input
            v-model="scriptForm.variable"
            placeholder="请输入参数,格式：参数1、参数2"
          />
        </el-form-item>

        <el-form-item label="输出结果" prop="result">
          <el-input v-model="scriptForm.result" :rows="10" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="executeSubmitForm">确 定</el-button>
        <el-button @click="executeCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 规则脚本对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="电路生成规则配置"
      :visible.sync="ruleScriptDialog"
      width="1200px"
      append-to-body
    >
      <rule-script-common
        :circuit-type-id="circuitTypeId"
        :scene-name="sceneName"
        :scene-id="sceneId"
        :scene-type="3"
        @close="ruleScriptDialog = false"
        ref="refRuleScript"
        v-if="ruleScriptDialog"
      />
    </el-dialog>

    <!-- 步骤条对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="步骤条"
      :visible.sync="stepBarDialog"
      width="1000px"
      style="height: 100vh"
      append-to-body
    >
      <div>
        <el-button-group style="display: flex">
          <el-button type="warning" plain size="mini" @click="circuitFilesImportDialog = true">上传电路文件</el-button>
          <el-button type="warning" plain size="mini" @click="fileLackList">数据清单-文件缺失列表</el-button>
          <el-button type="warning" plain size="mini" @click="noExistList">电路模板-未被记录列表</el-button>
          <el-button type="warning" plain size="mini" @click="documentLibraryList">文件库-文件缺失列表</el-button>
          <el-upload
            :action=importCircuitExcelUrl
            :headers="myHeaders"
            :data="importCircuitExcelData"
            style="width: 125px"
          ><el-button type="warning" plain  @click="submitGo">校验表格数据</el-button>
          </el-upload>

          <el-upload
            :action=importCircuitExcelUrl
            :headers="myHeaders"
            :data="importCircuitExcelData"
            style="width: 125px"
          ><el-button type="warning" plain @click="importCircuitExcelData.step='1'">数据录入</el-button>
          </el-upload>
        </el-button-group>

      </div>

      <el-steps :active="stepBarIndex" align-center finish-status="success">
        <el-step title="步骤1" description="上传目录结构"></el-step>
        <el-step title="步骤2" description="校验数据表格数据"></el-step>
        <el-step title="步骤3" description="数据表格数据录入数据库"></el-step>
        <el-step title="步骤3" description="上传目录"></el-step>
      </el-steps>

      <div
        v-loading="step0Loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%"
        v-if="stepBarIndex===0"
      >
        <div style="text-align: center;margin-top: 50px" v-show="firstUpload">
          <el-button type="primary" @click="triggerFileUpload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
          <input type="file" ref="fileInput" webkitdirectory directory multiple @change="uploadFolder" style="display: none;"/>
        </div>

        <el-result icon="success" subTitle="上传成功,点击返回可重新上传" v-show="firstSuccess">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="firstSuccess=false;firstUpload=true">返回</el-button>
            <el-button type="primary" size="medium" @click="stepBarNext">下一步</el-button>
          </template>
        </el-result>

        <el-result icon="error" subTitle="请选择正确的目录(circuitFiles)" v-show="firstError">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="firstError=false;firstUpload=true">重新上传</el-button>
          </template>
        </el-result>
      </div>

      <div
        v-loading="step1Loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%"
        v-if="stepBarIndex===1"
      >

        <div style="text-align: center;margin-top: 50px" v-show="twoUpload">
          <el-upload
            ref="stepBar2upload"
            :action=importCircuitExcelUrl
            :headers="myHeaders"
            :on-success="stepBar2Success"
            :data="importCircuitExcelData"
          >
            <el-button ref="stepBar2uploadbutton" type="success">上传<i class="el-icon-upload el-icon&#45;&#45;right"></i></el-button>
          </el-upload>
        </div>

        <el-result icon="success" title="校验通过,点击返回可重新校验" v-show="twoSuccess">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="twoSuccess=false;twoUpload=true">返回</el-button>
            <el-button type="primary" size="medium" @click="stepBarNext">下一步</el-button>
          </template>
        </el-result>

        <el-result icon="error" title="数据有误，请根据提示修改数据" :subTitle="twoErrorMsg"  v-show="twoError">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="lackListDownload">文件缺失列表下载</el-button>
            <el-button type="primary" size="medium" @click="noExistDownload">模板未被记录列表下载</el-button>
            <el-button type="primary" size="medium" @click="twoError=false;twoUpload=true">重新校验</el-button>
          </template>
        </el-result>
      </div>

      <div style="width: 100%" v-if="stepBarIndex===2">

        <div style="text-align: center;margin-top: 50px" v-show="threeUpload">
          <el-upload
            ref="stepBar3upload"
            :action=importCircuitExcelUrl
            :headers="myHeaders"
            :on-change="stepBar3Change"
            :on-success="stepBar3Success"
            :data="importCircuitExcelData"
          >
            <el-button type="success" @click="importCircuitExcelData.step='1'">
              上传
              <i class="el-icon-upload el-icon&#45;&#45;right"></i>
            </el-button>
          </el-upload>
        </div>

        <el-result icon="success" title="上传成功" v-show="threeSuccess">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="stepBarNext">下一步</el-button>
          </template>
        </el-result>

      </div>

      <div style="width: 100%" v-if="stepBarIndex===3">
        <uploader
          ref="uploadCircuitFilesImport"
          :options="this.circuitFilesImportOptions"
          @file-success="cfSuccess"
          @file-added="cfAdd"
        >
          <uploader-btn class="myUploader" :directory="true">选择文件目录</uploader-btn>
          <uploader-list>
            <!--通过slot-scope绑定文件实例-->
            <div slot-scope="props">
              <div v-for="(file,i) in props.fileList" :key="i" style="width: 100%">
                <el-row>
                  <el-col :span="3">
                    <el-button @click="clearCircuitFilesImportList(file)">删除</el-button>
                  </el-col>
                  <el-col :span="21">
                    <uploader-file :list="true" :file="file" ></uploader-file>
                  </el-col>
                </el-row>

              </div>
            </div>
          </uploader-list>
        </uploader>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listCircuit,
  getCircuit,
  delCircuit,
  addCircuit,
  updateCircuit,
  execute,
  uploadCircuitry,
  loadProperty,
  filesVerify,
  fileLackList,
  fileLackListDownload,
  noExistListDownload,
  noExistList,
  checkDocumentLibraryDownload,
  checkDocumentLibrary,
} from "@/api/expert/circuit";
import { allListCircuitType } from "@/api/expert/circuitType";
import { listRule } from "@/api/expert/rule";
import { listParam } from "@/api/expert/param";
import { getToken } from "@/utils/auth";
import attributeEdit from "./attributeEdit";
import ruleScriptCommon from "../common/ruleScriptCommon";
import request from "@/utils/request";

export default {
  name: "Circuit",
  components: {
    attributeEdit,
    ruleScriptCommon,
  },
  data() {
    return {
      circuitFilesImportOptions: {
        target: process.env.VUE_APP_BASE_API+"/file/uploadCircuitDirectory",
        testChunks: false,
        autoStart: false,
        headers: {
          Authorization: "Bearer " + getToken() ,
        },
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电路模板表格数据
      circuitList: [],
      // 电路类型表格数据
      circuitTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      openExecute: false,
      // 属性配置弹窗
      attributeEditDialog: false,
      // 电路生成规则配置弹窗
      ruleScriptDialog: false,
      // 电路文件导入配置弹窗
      circuitFilesImportDialog: false,
      // 电路文件缺失列表配置弹窗
      circuitFileLackListDialog: false,
      // 电路未被记录列表配置弹窗
      circuitNoExistListDialog: false,
      // 文件库文件缺失列表配置弹窗
      documentLibraryListDialog: false,
      // 步骤条配置弹框
      stepBarDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        state: null,
        insertTime: null,
        userId: null,
        path: null,
        circuitTypeId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 表单参数
      scriptForm: {
        circuitId: "",
        sceneName: "",
        runScript: "",
        inputParameter: "",
        variable: "",
      },
      // 表单校验
      scriptRules: {},
      // 脚本数据
      scriptList: [],

      dialogVisible: false,
      thumbPathDialogVisible: false,

      myHeaders: { Authorization: "Bearer " + getToken() },
      url: process.env.VUE_APP_BASE_API + "/file/uploadByFilepath",

      thumbnailFileList: [],
      thumbFileList: [],
      chartsFileList: [],
      projectFileList: [],
      bomFileList: [],
      netFileList: [],
      designatorsFileList: [],

      stateTypeEnum: this.GlobalVariable.stateTypeEnum,
      signalTypeEnum: this.GlobalVariable.signalTypeEnum,
      storageTypeEnum: this.GlobalVariable.storageTypeEnum,

      // 电路id
      circuitId: undefined,

      // 场景id
      sceneId: undefined,
      // 场景名称
      sceneName: undefined,
      // 电路类型id
      circuitTypeId: undefined,

      importCircuitExcelUrl: process.env.VUE_APP_BASE_API + "/circuitDesign/circuit/importExcel",

      uploadDateParam:{
        'bucketName':'circuitdesign',
        'filepath': ""
      },

      circuitImportUploadList: [],

      importShow: false,

      fileLackMap:{
        total: 1,
        page: 1,
        jsonArray:[]
      },
      noExistMap:{
        total: 1,
        page: 1,
        jsonArray:[]
      },
      documentLibraryJsonArray:[],
      documentLibraryLoading:true,
      stepBarIndex: 0,
      firstSuccess: false,
      firstError: false,
      firstUpload: true,
      twoSuccess: false,
      twoError: false,
      twoUpload: true,
      twoErrorMsg: "",
      threeUpload: true,
      threeSuccess: false,
      step0Loading:false,
      step1Loading:false,
      importCircuitExcelData:{
        "step":"0"
      }
    };
  },
  created() {
    this.getCircuitList();
    this.getCircuitTypeList();
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
      // this.$refs.upload.submit();
      // this.$refs.upload.submit();
    },
    // twoUploadClick(){
    //   this.$refs.circuitDataFromUpload.submit()
    // },
    listDownload(stringArray,fileName){
      stringArray.sort()
      // 将字符串数组转换为UTF-8编码的Uint8Array数组
      const encoder = new TextEncoder(); // TextEncoder用于将字符串转换为UTF-8编码的Uint8Array
      const uint8Arrays = stringArray.map(str => encoder.encode(str+'\n'));

      // 合并所有的Uint8Array为一个
      let length = 0;
      for (const uint8Array of uint8Arrays) {
        length += uint8Array.length;
      }
      const mergedUint8Array = new Uint8Array(length);
      let offset = 0;
      for (const uint8Array of uint8Arrays) {
        mergedUint8Array.set(uint8Array, offset);
        offset += uint8Array.length;
      }
      const blobObj = new Blob([mergedUint8Array], { type: 'text/plain;charset=utf-8' })
      // 创建一个链接并设置下载属性
      const downloadLink = document.createElement('a')
      let url = window.URL || window.webkitURL || window.moxURL // 兼容不同浏览器的 URL 对象
      url = url.createObjectURL(blobObj)
      downloadLink.href = url
      downloadLink.download = fileName // 设置下载的文件名
      // 将链接添加到 DOM 中，模拟点击
      document.body.appendChild(downloadLink)
      downloadLink.click()
      // 移除创建的链接和释放 URL 对象
      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(url)

    },
    noExistDownload(){
      noExistListDownload().then(responseMsg=>{
        let stringArray = responseMsg.data
        this.listDownload(stringArray,"未被记录列表")
      })
    },
    documentLibraryDownload(){
      checkDocumentLibraryDownload().then(responseMsg=>{
        let stringArray = responseMsg.data
        this.listDownload(stringArray,"文件库文件缺失列表")
      })
    },
    lackListDownload(){
      fileLackListDownload().then(responseMsg=>{
        let stringArray = responseMsg.data
        this.listDownload(stringArray,"文件缺失列表")
      })
    },
    fileLackPrevClick(){
      const pa = this.fileLackMap.page - 1
      this.getFileLackList(pa)
    },
    noExistPrevClick(){
      const pa = this.noExistMap.page - 1
      this.getNoExistList(pa)
    },
    fileLackNextClick(){
      const pa = this.fileLackMap.page + 1
      this.getFileLackList(pa)
    },
    noExistNextClick(){
      const pa = this.noExistMap.page + 1
      this.getNoExistList(pa)
    },
    noExistList(){
      this.circuitNoExistListDialog = true
      this.getNoExistList(1)
    },
    submitGo(){
      this.step1Loading = true
    },
    documentLibraryList(){
      this.documentLibraryListDialog = true
      checkDocumentLibrary().then(responseMsg=>{
        this.documentLibraryJsonArray = responseMsg.data
        this.documentLibraryLoading = false
      })
    },
    fileLackList(){
      this.circuitFileLackListDialog = true
      this.getFileLackList(1)
    },
    getFileLackList(page){
      fileLackList(page).then(responseMsg=>{
        this.fileLackMap = responseMsg.data
      })
    },
    getNoExistList(page){
      noExistList(page).then(responseMsg=>{
        this.noExistMap = responseMsg.data
      })
    },
    cfAdd(file){
      if(!file.relativePath.includes("circuitFiles")){
        file.cancel()
        this.$message.error("请选择正确的目录")
      }
    },
    cfSuccess(rootFile, file, message, chunk){
      if(message.includes("500")){
        this.$message.error(message)
      }
    },
    clearCircuitFilesImportList(file){
      file.cancel()
    },
    triggerFileUpload() {
      this.$refs.fileInput.click();
    },
    uploadFolder(event){
      this.step0Loading = true
      const files = event.target.files
      let fileNames = []
      for(let i = 0; i < files.length; i++){
        let re = files[i].webkitRelativePath.toString()
        if(re.includes("circuitFiles/")){
          fileNames[i]=(re.replace("circuitFiles/",""))
        }else {
          this.$message.error("请选择正确的目录")
          this.firstError=true
          this.firstUpload=false
          this.$refs.fileInput.value=null
          this.step0Loading = false
          return
        }
      }
      filesVerify({"fileNames": JSON.stringify(fileNames)}).then(re=>{
        this.$message.info(re.msg)
        // if(re.code === 200){
          this.firstSuccess=true
          this.firstUpload=false
          this.$refs.fileInput.value=null
        this.step0Loading = false
        // }else {
        //   this.firstError=true
        //   this.firstUpload=false
        //   this.$refs.fileInput.value=null
        // }
      })
    },
    circuitFilesAdd(files, fileList){
      for(let f of files){
        f.pause()
        console.log("1")
        f.resume()
      }
    },
    uploadDateSet(){
      this.uploadDateParam.filepath = new Date().toLocaleDateString()
        + "/"
        + new Date().getTime()
        + "_"
    },
    /** 查询电路模板列表 */
    getCircuitList() {
      this.loading = true;
      listCircuit(this.queryParams).then((response) => {
        this.circuitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询电路类型列表 */
    getCircuitTypeList() {
      allListCircuitType().then((response) => {
        this.circuitTypeList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        state: null,
        insertTime: null,
        userId: null,
        projectPath: null,
        thumbnailPath: null,
        thumbPath: null,
        chartsPath: null,
        bomPath: null,
        netPath: null,
        designatorsPath: null,
        circuitTypeId: null,
        signalType: null,
        storageType: null,
        storageCapacity: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if(this.queryParams.name === 'wu5'){
        this.importShow ? this.importShow = false : this.importShow = true
        this.queryParams.name = ''
      }
      this.queryParams.pageNum = 1;
      this.getCircuitList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电路模板";

      this.thumbnailFileList = [];
      this.thumbFileList = [];
      this.chartsFileList = [];
      this.projectFileList = [];
      this.bomFileList = [];
      this.netFileList = [];
      this.designatorsFileList = [];
    },
    urlChange(str){
      if(str.indexOf("=") !== -1 && str.indexOf("&") !== -1){
        return str.substring(str.indexOf("=")+1,str.indexOf("&"))
      }
      return str
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCircuit(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改电路模板";

        this.thumbnailFileList = [];
        this.thumbFileList = [];
        this.chartsFileList = [];
        this.projectFileList = [];
        this.bomFileList = [];
        this.netFileList = [];
        this.designatorsFileList = [];

        if (this.form.thumbnailPath) {
          let j = { name: this.urlChange(this.form.thumbnailPath), url: this.form.thumbnailPath, };
          this.thumbnailFileList.push(j);
        }

        if (this.form.thumbPath) {
          let j = { name: this.urlChange(this.form.thumbPath), url: this.form.thumbPath };
          this.thumbFileList.push(j);
        }

        if (this.form.chartsPath) {
          let j = { name: this.urlChange(this.form.chartsPath), url: this.form.chartsPath };
          this.chartsFileList.push(j);
        }
        if (this.form.projectPath) {
          let j = { name: this.form.projectPath, url: this.form.projectPath };
          this.projectFileList.push(j);
        }
        if (this.form.bomPath) {
          let j = { name: this.form.bomPath, url: this.form.bomPath };
          this.bomFileList.push(j);
        }
        if (this.form.netPath) {
          let j = { name: this.form.netPath, url: this.form.netPath };
          this.netFileList.push(j);
        }
        if (this.form.designatorsPath) {
          let j = {
            name: this.form.designatorsPath,
            url: this.form.designatorsPath,
          };
          this.designatorsFileList.push(j);
        }
      });
    },
    /** 执行脚本弹窗 */
    execute(row) {
      this.openExecute = true;
      this.scriptForm = {
        circuitId: row.id,
        sceneName: row.name,
        runScript: "",
        inputParameter: "",
        variable: "",
        result: "",
      };

      let queryRuleParams = {
        pageNum: 1,
        pageSize: 99999,
        circuitId: row.id,
        name: null,
        runEnv: null,
        runScript: null,
        state: null,
        insertTime: null,
        userId: null,
        priority: null,
      };
      listRule(queryRuleParams).then((response) => {
        this.scriptList = response.rows;
      });

      let paramQueryParams = {
        pageNum: 1,
        pageSize: 99999,
        name: null,
        type: null,
        priority: null,
        circuitId: row.id,
        inputMinValue: null,
        inputMaxValue: null,
      };
      listParam(paramQueryParams).then((response) => {
        if (response.rows) {
          console.log(response.rows);
          for (let i = 0; i < response.rows.length; i++) {
            if (response.rows.length - 1 == i) {
              this.scriptForm.inputParameter += response.rows[i].name;
            } else {
              this.scriptForm.inputParameter =
                this.inputParameter + response.rows[i].name + "、";
            }
          }
        }
      });
    },
    /** 规则脚本弹窗 */
    openAttributeEditDialog(row) {
      this.circuitId = row.id;
      this.attributeEditDialog = true;
    },
    formUrlChange(str){
      if(str === null || str === ''){
        return ''
      }
      const start = str.indexOf('circuitdesign') === -1 ? 0 : str.indexOf('circuitdesign')
      const end = str.indexOf('&token=') === -1 ? str.length : str.indexOf('&token=')-1
      return str.substring(start,end)
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.form.circuitTypeId === null || this.form.circuitTypeId === ''){
            this.$modal.msg("电路类型不可为空")
            return
          }

          if (this.form.storageCapacity != null) {
            this.form.storageCapacity = parseInt(this.form.storageCapacity);
          }

          this.form.thumbnailPath = this.formUrlChange(this.form.thumbnailPath)
          this.form.thumbPath = this.formUrlChange(this.form.thumbPath)
          this.form.projectPath = this.formUrlChange(this.form.projectPath)
          this.form.chartsPath = this.formUrlChange(this.form.chartsPath)
          this.form.bomPath = this.formUrlChange(this.form.bomPath)
          this.form.netPath = this.formUrlChange(this.form.netPath)
          this.form.designatorsPath = this.formUrlChange(this.form.designatorsPath)

          if (this.form.id != null) {
            updateCircuit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getCircuitList();
            });
          } else {
            addCircuit(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getCircuitList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除电路模板编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCircuit(ids);
        })
        .then(() => {
          this.getCircuitList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "edsta/circuit/export",
        {
          ...this.queryParams,
        },
        `edsta_scene.xlsx`
      );
    },
    /** 执行脚本 */
    executeSubmitForm() {
      this.$refs["scriptForm"].validate((valid) => {
        if (valid) {
          execute(
            this.scriptForm.circuitId,
            this.scriptForm.runScript,
            this.scriptForm.variable
          ).then(
            (response) => {
              console.log("-----------");
              console.log(response);
              this.scriptForm.result = response.msg + "";
            },
            (error) => {
              console.log("---------------------------");
              console.log(error);
              this.scriptForm.result = error + "";
            }
          );
        }
      });
    },
    /** 取消 */
    executeCancel() {
      this.openExecute = false;
      this.scriptForm = {
        id: null,
        name: null,
        state: null,
        insertTime: null,
        userId: null,
        path: null,
      };
      this.resetForm("scriptForm");
    },

    closeAttributeEditDialog() {
      this.attributeEditDialog = false;
    },
    // 略缩图删除
    thumbnailHandleRemove(file, fileList) {
      // this.thumbnailFileList = fileList
      this.form.thumbnailPath = "";
    },
    // 缩略图上传成功
    thumbnailUploadSuccess(response, file, fileList) {
      this.form.thumbnailPath = file.response.data.url;
      this.uploadDateParam.filepath = ""

      // console.log(response)
      // console.log(file)
      // console.log(fileList)
      // this.thumbnailFileList = fileList
    },

    // 方案封面图删除
    thumbHandleRemove(file, fileList) {
      this.form.thumbPath = "";
    },
    // 方案封面图上传成功
    thumbUploadSuccess(response, file, fileList) {
      this.form.thumbPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },

    // 图表删除
    chartsHandleRemove(file, fileList) {
      this.form.chartsPath = "";
    },
    // 图表上传成功
    chartsUploadSuccess(response, file, fileList) {
      this.form.chartsPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },

    // 工程文件删除
    projectHandleRemove(file, fileList) {
      this.form.projectPath = "";
    },
    // 工程文件上传成功
    projectUploadSuccess(response, file, fileList) {
      this.form.projectPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },

    // 工程文件删除
    bomHandleRemove(file, fileList) {
      this.form.bomPath = "";
    },
    // 工程文件上传成功
    bomUploadSuccess(response, file, fileList) {
      this.form.bomPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },

    // 网络替换表文件删除
    netHandleRemove(file, fileList) {
      this.form.netPath = "";
    },
    // 网络替换表上传成功
    netUploadSuccess(response, file, fileList) {
      this.form.netPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },
    // 位号替换表文件删除
    designatorsHandleRemove(file, fileList) {
      this.form.designatorsPath = "";
    },
    // 位号替换表上传成功
    designatorsUploadSuccess(response, file, fileList) {
      this.form.designatorsPath = file.response.data.url;
      this.uploadDateParam.filepath = ""
    },

    // 输入参数规则配置
    openDataRules(row) {
      this.sceneId = row.id;
      this.sceneName = row.name;
      this.circuitTypeId = row.circuitType.id;
      this.ruleScriptDialog = true;
    },
    // 文件上传成功回调
    onSuccess(response, file, fileList) {
      if(response.msg === null && this.importCircuitExcelData.step === "0"){
        this.importCircuitExcelData.step = '1-3'
        this.submitUpload()
      }
      this.circuitImportUploadList = []
    },
    stepBar3Change(){
      this.threeUpload = false
      this.threeSuccess = true
      this.$refs.stepBar3upload.clearFiles()
    },
    stepBar2Success(response, file, fileList) {
      this.twoUpload = false

      if(response.msg == null || response.msg === ""){
        this.twoSuccess = true
        this.step1Loading = false
      }else {
        this.twoErrorMsg = response.msg
        this.twoError = true
        this.step1Loading = false
      }
      this.$refs.stepBar2upload.clearFiles()
      this.step1Loading = false
    },
    stepBar3Success(response, file, fileList) {

    },
    circuitParamRefresh(){
      loadProperty()
      this.$message.success("属性加载已启动需耗时1-2分钟")
    },
    stepBarNext(){
      this.stepBarIndex = this.stepBarIndex + 1
    }
  },
};
</script>

<style scoped>


/keep/.el-input__inner{
  color: black;
}
</style>
